package cn.uin.infrastructure.adapter.port;

import cn.uin.domain.family.adapter.port.IFamilyNotificationPort;
import cn.uin.domain.family.model.valobj.FamilyAddStatusTypeEnum;
import cn.uin.domain.family.model.valobj.FamilyRoleTypeEnum;
import cn.uin.infrastructure.dao.HomeFamilyListDao;
import cn.uin.infrastructure.dao.HomeUserDao;
import cn.uin.infrastructure.dao.po.HomeFamilyList;
import cn.uin.infrastructure.dao.po.HomeUser;
import cn.uin.infrastructure.redis.IRedisService;
import cn.uin.types.common.RedisConstants;
import cn.uin.types.common.TextConstants;
import cn.uin.types.enums.ResponseCode;
import cn.uin.types.exception.AppException;
import cn.uin.types.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @ClassName FamilyNotificationPort
 * @Description:家庭通知服务实现
 * @Author: Administrator
 * @CreateDate: 2025/11/12 13:59
 * @Version: 1.0
 */
@Slf4j
@Service
public class FamilyNotificationPort implements IFamilyNotificationPort {

	@Resource
	private JavaMailSender mailSender;

	@Resource
	private HomeUserDao homeUserDao;

	@Resource
	private HomeFamilyListDao homeFamilyListDao;

	@Resource
	private IRedisService redisService;

	@Resource
	private SpringTemplateEngine templateEngine;

	@Value("${spring.mail.username}")
	private String emailFrom;

	@Value("${email.activate.link.add-family}")
	private String activationLink;

	@Override
	public boolean sendEmailLink(Long familyId, String email) {
		// TODO 后续调整为异步MQ处理
		try {
			HomeUser homeUser = homeUserDao.queryUserByEmail(email);
			if (ObjectUtils.isEmpty(homeUser)) {
				throw new AppException(ResponseCode.A0010.getCode(), ResponseCode.A0010.getInfo());
			}
			MimeMessage message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
			helper.setTo(email);
			helper.setSubject(TextConstants.FAMILY_EMAIL_SUBJECT);
			helper.setFrom(emailFrom);
			// 生成随机数作为token并写入redis
			String token = UUIDUtils.generateRawUUID();
			redisService.setValue(RedisConstants.ADD_FAMILY_TOKEN + email, token, 259200000L);
			helper.setText(buildEmailContext(familyId, email, activationLink, token), true); // true 表示内容是HTML格式
			mailSender.send(message);

			// 同步写入成员数据(已邀请,还未进入状态)
			HomeFamilyList homeFamilyList = HomeFamilyList.builder()
					.userId(homeUser.getId())
					.familyId(familyId)
					// 被邀请人员默认为成员
					.role(FamilyRoleTypeEnum.MEMBER.getInfo())
					.addTime(new Date())
					.addStatus(FamilyAddStatusTypeEnum.INVITED.getCode())
					.build();
			homeFamilyListDao.insert(homeFamilyList);
			return true;
		} catch (MessagingException e) {
			log.error("发送邮件失败:{}", e.getMessage());
			return false;
		}
	}

	/**
	 * 构建邮件内容
	 * @param email
	 * @param activationLink
	 * @return
	 */
	private String buildEmailContext(Long familyId, String email, String activationLink, String token) {
		HomeUser homeUser = homeUserDao.queryUserByEmail(email);
		Context context = new Context();
		context.setVariable("name", homeUser.getUsername());
		context.setVariable("activationLink", activationLink);
		context.setVariable("token", token);
		context.setVariable("email", email);
		context.setVariable("familyId", familyId);
		return templateEngine.process("email-template.html", context);
	}
}
